package com.sydsen.imager.painter;

import com.sydsen.imager.Canvas;
import com.sydsen.imager.ImageOptions;
import com.sydsen.imager.elements.Image;
import com.sydsen.imager.util.ImageUtils;

import java.awt.image.BufferedImage;

/**
 * @Auther: syh
 * @Date: 2021/11/1
 * @Description:
 */
public class ImagePainter extends AbstractPainter<Image> {

    @Override
    protected void doDraw(Canvas canvas, Image element) throws Exception {
        BufferedImage image = element.getImage();

        int width = getElementWidth(element);
        int height = getElementHeight(element);
        //设置圆角
        if (element.radius() > 0) {
            image = ImageUtils.makeRoundCorner(image, width,
                    height, element.radius());
        }

        //高斯模糊
        if (element.noise() > 0) {
            image = ImageUtils.makeBlur(image, element.noise());
        }

        // 翻转
        if (!ImageOptions.Flip.DEFAULT.equals(element.flip())) {
            image = ImageUtils.flipImage(image, element.flip());
        }

        // 去色
        if (element.gray()) {
            image = ImageUtils.toGray(image);
        }

        canvas.getGraphics().drawImage(image, element.x(), element.y(), width, height, null);

    }

    @Override
    protected int getElementWidth(Image imageElement) {

        BufferedImage image = imageElement.getImage();

        switch (imageElement.zoom()) {
            case Origin:
                return image.getWidth();
            case Height:
                int height = imageElement.height();
                return image.getWidth() * height / image.getHeight();
            case Width:
            case WidthHeight:
                return imageElement.width();
            default:
                throw new UnsupportedOperationException("不支持的缩放类型");
        }
    }

    @Override
    protected int getElementHeight(Image imageElement) {

        BufferedImage image = imageElement.getImage();

        switch (imageElement.zoom()) {
            case Origin:
                return image.getHeight();
            case Width:
                int width = imageElement.width();
                return image.getHeight() * width / image.getWidth();
            case Height:
            case WidthHeight:
                return imageElement.height();
            default:
                throw new UnsupportedOperationException("不支持的缩放类型");
        }
    }

}
